<template>
  <div id="container" class="cards-container">

    <div class="timeGroup">
      <div class="time-display">
        {{ formattedTime }}
      </div>

      <el-button
          plain
          type="primary"
          :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
          @click="startTimer"
      >
        {{ isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始倒计时' : (isRunning ? '运行中' : '启动') }}
      </el-button>

      <el-button
          plain
          type="warning"
          :disabled="!isRunning"
          @click="pauseTimer"
      >
        暂停
      </el-button>

      <el-button
          plain
          :disabled="isRunning"
          @click="resetTimer"
      >
        重置
      </el-button>
    </div>

    <!-- 状态按钮 -->
    <div class="controls">
      <el-check-tag type="primary" >
        查询内容--书名:{{queryParam.book}}--单元:{{queryParam.unit}}--总数:{{total}}--当前:{{cards.length}}
      </el-check-tag>
    </div>

    <!-- 控制按钮 -->
    <div class="loadDataClass">
      <button @click="selectData">查询数据</button>

      <el-select v-if="!selectDataStatus" style="width: 100px;" clearable v-model="queryParam.book" placeholder="书名">
        <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
      </el-select>

      <el-select v-if="!selectDataStatus" style="width: 100px" clearable v-model="queryParam.unit" placeholder="单元名称">
        <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
      </el-select>

      <button v-if="!selectDataStatus" style="background-color: #52c41a" @click="loadData">确认</button>
    </div>

    <!-- 随机分布的卡片 -->
    <!-- v-memo="[]" v-memo 仅当依赖项（这里是空数组）变化时才渲染 -->
    <div
      v-for="(card, index) in cards" 
      :key="index"
      class="card"
      :style="getCardStyle(card, index)"
      @mouseenter="handleMouseEnter(index)"
      @mouseleave="handleMouseLeave(index)"
      @click="handleCardClick(index)"
    >
      <div class="card-inner">
        <div class="card-content">
          <h1 style="font-size: 36px">{{ card.name }}<span @click="handleColumnAudio(card)" style="float: right;color: #1c84c6;font-size: 14px;cursor: pointer">发音</span></h1>
          <p style="text-align: center;color: #421f7d;font-size: 18px"><span style="font-size: 14px" v-if="card.type !== null">词性</span>
            {{card.type === null ? '': '--- ' +  card.type }}
          </p>

          <p style="font-size: 24px;color: #23c6c8;text-align: center">{{ card.chinese }}</p>
          <p>
            <span v-if="card.name.toString().indexOf(' ') === -1 && card.name.toString().indexOf('/') === -1 && card.name.toString().indexOf('-') === -1"
                  @click="getNetworkInfo(card)" style="float: right;color: darkmagenta;cursor: pointer">更多<span v-if="!card.loadMore">∨</span></span>
          </p>
          <a style="font-size: 14px" v-if="card.loadMore"><span>例句</span><br></a>
          <div style="color: #718096" v-if="card.loadMore" v-html="card.loadMoreHtml"></div>
          <button @click="wordStudIed(index,$event)" v-if="card.isActive" style="cursor: pointer;background-color: #52c41a;color: white;border: 1px solid">掌握</button>
        </div>
      </div>
    </div>

    <div v-if="cards.length === 0" style="width: 100vw;height: 100vh;align-items: center;display: flex;justify-content: center">
      <el-empty :image-size="400" description="恭喜你已学完本单元全部的单词">
        <el-button @click="submitRecord" type="success">提交记录</el-button>
      </el-empty>
    </div>

    <!-- 重置按钮 -->
    <button
      class="reset-btn"
      @click="resetCardPositions"
    >
      <i class="fas fa-redo"></i> 重新排列
    </button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {
  putStudyList,
  getMessageBoxContent,
  getPageUnit,
  getWordInfoMore,
  getWordSentence,
  handleColumnAudio
} from "@/api/word/index.js";
import {ElMessageBox} from "element-plus";
import {addStudy_record, getUsedTime} from "@/api/word/wordRecord.js";
import {parseTime} from "@/utils/ruoyi.js";
import {useTimerStore} from "@/store/timer.js";

// 卡片数据
const cards = ref([]);
const selectDataStatus = ref(true);
const pageData = ref([]);
const route = useRoute()
let studyRecord = ref([])
let practiceId = ref(null)
let correctNum = ref(0)
let testStartTime = ref(null)
let testEndTime = ref(null)
let testStartTimeStatus = ref(true)

const timerStore = useTimerStore();
timerStore.isCountdown = false;
// 从 store 中解构 actions
const { startTimer, pauseTimer, resetTimer, toggleMode, setInitialTime } = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const { formattedTime, isRunning, isCountdown, initialTime, currentTime } = storeToRefs(timerStore); // 添加 currentTime


let recordFrom = ref({})

const {proxy} = getCurrentInstance()
let queryParam = ref({
  unit: '',
  boot: ''
})
let total = ref(0)

// 窗口尺寸
const windowSize = ref({
  width: 0,
  height: 0
});

// 生成卡片随机位置和旋转角度
const generateCardPositions = () => {
  // 获取当前窗口尺寸
  windowSize.value.width = window.innerWidth;
  windowSize.value.height = window.innerHeight;

  // 计算最大可放置位置，确保卡片不会超出屏幕
  const maxLeft = windowSize.value.width - 300 - 240; // 减去边距
  const maxTop = windowSize.value.height - 250 - 100;
  cards.value = []
  // console.log(pageData)
  pageData.value.forEach(item => {
    item.loadMore = false
    item.isHovered = false
    item.isActive = false
    item.loadMore = false
    item.loadMoreHtml = ''
    item.width = 300
    item.height = 250

    // 生成随机位置（确保在屏幕内）
    item.left = Math.floor(Math.random() * maxLeft) + 20; // 最小边距
    item.top = Math.floor(Math.random() * maxTop) + 20;

    // 生成随机旋转角度（-25到25度之间）
    item.rotation = parseInt(Math.random() * 50 - 25);

    // 生成随机z-index值，创建堆叠效果
    item.zIndex = Math.floor(Math.random() * 10) + 1;
    // item.title = item.title
    cards.value.push(item)
  })
};

// 获取卡片样式
const getCardStyle = (card, index) => {
  // const state = cardStates.value[index];
  return {
    width: `${card.width}px`,
    height: `${card.height}px`,
    left: `${card.left}px`,
    top: `${card.top}px`,
    // transform: `rotate(${card.rotation}deg) ${state.isHovered ? 'scale(1.05)' : ''}`,
    transform: `rotate(${card.rotation}deg) ${card.isHovered ? 'scale(1.05)' : ''}`,
    // zIndex: state.isActive ? 100 : (state.isHovered ? card.zIndex + 10 : card.zIndex),
    zIndex: card.isActive ? 100 : (card.isHovered ? card.zIndex + 10 : card.zIndex),
    // 随机柔和背景色
    backgroundColor: `hsl(${Math.random() * 360}, 20%, 95%)`
  };
};

// 鼠标进入卡片
const handleMouseEnter = (index) => {
  cards.value[index].isHovered = true;
  cards.value[index].rotation = 0;
  // cards.value[index].isActive = true;
};

// 鼠标离开卡片
const handleMouseLeave = (index) => {
  cards.value[index].isHovered = false;
  cards.value[index].rotation = parseInt(Math.random() * 30 - 15);
};

// 点击卡片
const handleCardClick = (index) => {
  // 重置所有卡片的活跃状态
  cards.value.forEach((state, i) => {
    state.isActive = i === index;
  });
  // 如果卡片被激活，置于顶层
  cards.value[index].zIndex = 100;
};

// 重置卡片位置
const resetCardPositions = () => {
  resetTimer()
  // 重新生成位置
  generateCardPositions();
  //重置正确个数
  correctNum.value = 0
};

// 初始化和窗口大小变化时重新布局
onMounted(() => {
  handleQuery()
  practiceId.value = Math.random().toString().substring(2)
  window.addEventListener('resize', generateCardPositions);
});

function handleQuery() {
  queryParam.value.unit = route.query.unit
  queryParam.value.book = route.query.book
  selectWordData()
}

//提交记录-全部-交互
function submitRecord() {
  // console.log(studyRecord)
  if (studyRecord.value.length <= 0) {
    proxy.$modal.msgWarning("未有学习记录")
    return
  }
  proxy.$modal.confirm('是否确认提交').then(function () {
    testEndTime.value = Date.now()
    pauseTimer()
    putStudyList(studyRecord.value)
    setupMySQLData()
  }).catch(function () {
    proxy.$modal.msg("取消提交")
  })
}

//构建mysql所需的数据
function setupMySQLData() {
  recordFrom.value.book = queryParam.value.book
  recordFrom.value.unit = queryParam.value.unit
  recordFrom.value.wordNum = total.value
  recordFrom.value.practice = practiceId.value
  recordFrom.value.usedTime = getUsedTime((testEndTime.value - testStartTime.value) / 1000)
  recordFrom.value.correctNum = correctNum.value
  recordFrom.value.correctRate = correctNum.value / total.value
  // console.log(recordFrom.value)
  handleInsertRecordData(recordFrom.value)
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  data.type = 'middle'
  addStudy_record(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      correctNum.value = 0
      practiceId.value = Math.random().toString().substring(2)
      proxy.$modal.msgSuccess("提交成功")
      recordFrom.value = {}
      studyRecord.value = null
      testStartTimeStatus.value = true
      testStartTime.value = Date.now()
    }
  })
}

function selectWordData(){
  getPageUnit(queryParam.value).then((res) => {
    if (res.code === 200) {
      pageData.value = res.data
      total.value = res.data.length
      generateCardPositions();
    }
  })
}

function selectData(){
  selectDataStatus.value = !selectDataStatus.value;
}

function loadData(){
  // console.log(queryParam.value)
  if (queryParam.value.unit === '' || queryParam.value.book === '') {
    return;
  }
  selectDataStatus.value = true;
  selectWordData()
}

function wordStudIed(item,event){
  let itemData = cards.value[item];
  // console.log(itemData)
  itemData['practiceId'] = practiceId.value
  itemData['time'] = parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}');
  delete itemData['_id']
  //学习个数

  correctNum.value ++
  //记录首次点击的时间

  if (testStartTimeStatus.value) {
    testStartTime.value = Date.now()
    testStartTimeStatus.value = false
    startTimer()
  }
  studyRecord.value.push(itemData)

  cards.value.splice(item, 1);
  event.stopPropagation(); // 阻止事件冒泡到父元素
}

function getNetworkInfo(row) {
  let word = row.name
  if (word === null || word === undefined) {
    return
  }
  if (word.toString().indexOf(" ") > -1
      || word.toString().indexOf("/") > -1
      || word.toString().indexOf("-") > -1) {
    proxy.$modal.msgWarning("不支持短语查询")
    return
  }
  row.loadMore = true
  getWordInfoMore(word).then(res => {
    if (res.code === 200) {
      // console.log(res.data)
      let wordInfoMore = getMessageBoxContent(res.data);
      row.loadMoreHtml = getWordSentence(res.data.sentences);
      ElMessageBox.alert(wordInfoMore, word, {
        confirmButtonText: 'OK',
        dangerouslyUseHTMLString: true,
        mask: false, // 关闭遮罩层
        draggable: true,
        customStyle: {
          'width' : '1600px',
        },
      })
    } else {
      proxy.$modal.msgWarning("请求失败")
    }
  });
}
</script>

<style scoped>
.cards-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
  background-image:
    radial-gradient(#e0e5ec 1px, transparent 1px),
    radial-gradient(#e0e5ec 1px, transparent 1px);
  background-size: 50px 50px;
  background-position: 0 0, 25px 25px;
}

.card {
  position: absolute;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  cursor: crosshair;
  overflow: auto;
}

.card-inner {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-content {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card h3 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-weight: 600;
}

.card p {
  margin: 0;
  font-size: 14px;
  color: #718096;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

/* 活跃状态的卡片样式 */
.card:has(+ .card-active) {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

/* 重置按钮样式 */
.reset-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 16px;
  background-color: white;
  border: none;
  border-radius: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
  z-index: 101;
}

.reset-btn:hover {
  background-color: #f7fafc;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.reset-btn i {
  font-size: 16px;
}

.time-display {
  font-size: 1.5rem;
  font-weight: bold;
  color: #323233;
  border: none;
  border-radius: 12px;
  background-color: #ffffff;
  min-width: 120px;
  letter-spacing: 3px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.timeGroup{
  position: absolute;
  top: 15px;
  left: 200px;
  transform: translateX(-50%);
  z-index: 101;
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 状态按钮 */
.controls {
  position: fixed;
  bottom: 20px;
  left: 400px;
  transform: translateX(-50%);
  z-index: 101;
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 控制按钮 */
.loadDataClass {
  position: absolute;
  top: 15px;
  left: 45%;
  transform: translateX(-50%);
  z-index: 101;
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loadDataClass button {
  padding: 0 16px;
  border: none;
  border-radius: 4px;
  height: 30px;
  line-height: 30px;
  background-color: #42b983;
  color: white;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.loadDataClass button:hover {
  background-color: #359e75;
}

</style>
